package edu.chen.filter;

import edu.chen.bean.User;
import edu.chen.service.impl.UserServiceImplByHibernate;
import edu.chen.util.CookieUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录权限拦截器
 * 1、对所有通向注册界面,验证注册，以及一些静态资源的请求直接放行
 * 2、访问其他页面的,先检查当前对话中有没有“loginUser”的属性,有则直接登录
 * 3、若当前会话没有登录过,在查找本地Cookie,有没有“autoLogin”
 */
public class LoginFilter implements Filter {
    private UserServiceImplByHibernate userServiceImplByHibernate;

    /**
     * 因为Filter比Bean更早加载,所以在不做代理配置的时候,此处注入为null
     */
//    public void setUserServiceImplByHibernate(UserServiceImplByHibernate userServiceImplByHibernate) {
//        System.out.println("注入成功");
//        this.userServiceImplByHibernate = userServiceImplByHibernate;
//    }

    public void init(FilterConfig config) throws ServletException {
        /**
         * 初始化的时候手动注入userServiceImplByHibernate
         */
        ServletContext context = config.getServletContext();
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
        userServiceImplByHibernate = (UserServiceImplByHibernate) webApplicationContext.getBean("userServiceImplByHibernate");
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;

        /**
         * 1、排除指向login页面的请求
         */
        String uri = request.getRequestURI();
//        System.out.println(uri);
//        System.out.println(userServiceImplByHibernate);
        if(uri.endsWith("login.jsp") || uri.endsWith("login") || uri.endsWith(".js") ||
                uri.endsWith("verifyLogin") || uri.endsWith("spring/")) {
            chain.doFilter(req,resp);
            return;
        }

        /**
         * 2、判断本次访问的Session中有没有loginUser
         * 如果Session中存在loginUser说明已经登录过,所以直接放行
         * 只有获取到user才放心,login页面跳转放在最后
         */
        HttpSession session = request.getSession();
        User userForSession = (User) session.getAttribute("loginUser");
        if(null != userForSession){
            if(userServiceImplByHibernate.verifyUser(userForSession)) {
                System.out.println("从本次访问中获取user");
                chain.doFilter(req, resp);
                return;
            }else{
                System.out.println("本地会话loginUser错误");
            }
        }

        /**
         * 3、Cookie自动登录
         * 1、获取名为“autoLogin”的Cookie
         * 2、获取其中的值，验证并登录
         */
        Cookie autoLogin = new CookieUtils().getCookieByName(request,"autoLogin");
        if(autoLogin != null){
            //从Cookie中提取信息
            String data = autoLogin.getValue();
            //拼装成User
            String[] userData = data.split("#");
            User user = new User();
            user.setUsername(userData[0]);
            user.setPassword(userData[1]);
            //验证用户
            if(userServiceImplByHibernate.verifyUser(user)){
                System.out.println("从本地Cookie中获取信息成功");
                chain.doFilter(req,resp);
                return;
            }
        }

        response.sendRedirect("/spring/login");


    }

}
